package tools.clustering.isodata.workStrategies;

import java.util.ArrayList;

import tools.clustering.isodata.isodata_data;
import tools.utils.DoubleMatrix;
import neuro.uu.se.utils.WorkStrategy;

public class isodata_assigning implements WorkStrategy{

	public Object perform(Object object)throws Exception{
		isodata_data a=(isodata_data) object;
//		System.out.println(a.getCentroids().getDistance(new Integer(2), new Integer(2)));
		if(a.getCluster().intValue()==0){
//		if(true){
			double min=9999999,cur=0;
			Integer position=new Integer(0);
			for (Integer i : a.getCentroids().keySet()) {
				if(a.getCentroids().getDistance(i,position)<=4*min){
					cur=a.distanceTo(((DoubleMatrix)a.getCentroids().getData(i)));
//					System.out.println(cur+"\t"+i+"\t"+position);
					if(cur<min){
						min=cur;
						position=new Integer(i.intValue());
					}
				}
			}
//			try{
			a.setCluster(new Integer(a.getCentroids().getCluster(position).intValue()));
//			}catch (Exception e) {
//				System.out.println(position);
//				System.out.println(a.getCentroids().getCluster(position).getClass().getName());
//			}
			a.setDistanceToCentroid(min);
		}else{
			int i=0;
//			try{
			ArrayList<Integer> order=a.getOrder();
			double min=a.distanceTo( (DoubleMatrix)a.getCentroids().getData(order.get(0)) ),cur;
			Integer position=order.get(0);
			for( i=1;i<a.getCentroids().size();i++){
				if(a.getDistances().get(0,i)<=4*min){
					cur=a.distanceTo((DoubleMatrix)a.getCentroids().getData( (Integer)order.get(i) ));
					if(cur<min){
						min=cur;
						position=order.get(i);
						for(int j=i+1;j<order.size();j++){
							if(a.getCentroids().getDistance(order.get(j),position)<=4*min){
								cur=a.distanceTo(((DoubleMatrix)a.getCentroids().getData( order.get(j) )));
								if(cur<min){
									min=cur;
									position=order.get(j);
								}
							}
						}
						break;
					}
				}else{
					break;
				}
			}
			a.setCluster(new Integer(a.getCentroids().getCluster(position).intValue()));
			a.setDistanceToCentroid(min);
//			}catch(NullPointerException e){
//				e.printStackTrace();
//				for (Integer blaj : a.getOrder()) {
//					System.out.print(blaj+"\t");
//				}
//				System.out.println(a.getOrder().size());
//				System.out.println( a.getCentroids().hasKey(a.getOrder().get(i)) );
//				System.out.println( a.getCluster() );
//			}
		}
		return null;
	}
}
